import { Component } from '@angular/core';

import { AlertController, ModalController, NavController, NavParams } from 'ionic-angular';

import { MarketingDailySaveService } from './save.service';

import { Common } from '../../../../providers/common';

import { Storage } from '@ionic/storage';

import _ from 'lodash';
import {ContactChoosePage} from "../../../contact/choose/choose.component";
import {MarketingOrganizationChoosePage} from "../../organization/choose/choose.component";
import {MarketingAgencyChoosePage} from "../../agency/choose/choose.component";

@Component({
  selector: 'page-marketing-daily-save',
  templateUrl: './save.html',
  providers: [MarketingDailySaveService]
})
export class MarketingDailySavePage {
	moa_page_name: any = "page-marketing-daily-save";
  moa_page_explain: any = "";

  defaultEmpByTree = [];
  defaultImpProject = [];

  saveEntity = null;
  pageField = null;//页面显示需要用到额外字段
  maxDate = "";
  contactTypeList = [];//接触方式字典

  organizationContacts = [];
  agencyContacts = [];

  isEditData = false;

  title = "";

  customNames1: string = "";
  customNames2: string = "";

  constructor(
    public alertCtrl: AlertController,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    private navParams: NavParams,
    public common: Common,
    public storage: Storage,
    public saveService: MarketingDailySaveService
  ) {
    this.maxDate = this.common.getNowFormatDate();
    let that = this;
    that.initSaveEnity();
    this.saveService.getContackType().subscribe(data => {
      var dataList = [];
      _.forEach(data, function (i) {
        let d = i.split("|");
        if (d[0] != "*") {
          dataList.push(d);
        }
      });
      this.contactTypeList = dataList;

      let isEdit = that.navParams.get("isEdit");
      if (isEdit) {
        let detail = that.navParams.get("detail");
        that.isEditData = true;
        that.title = "修改工作日报";
        that.setSaveEntity(detail);
      } else {
        that.title = "新增工作日报";

        this.storage.get("userInfo").then(user => {
          console.log(user);
          that.saveEntity.login_nm_i = user.loginid;
          that.pageField.EMPLOYEE_i_name = user.emname;
          that.saveService.getUsrIDByLoginNM(user.loginid).subscribe(usr_id => {
            console.log(usr_id);
            _.forEach(usr_id, function (i) {
              let d = i.split("|");
              that.saveEntity.EMPLOYEE_i = d[0];
            });
          });

          let delfaultUser = {
            empid: user.empid,
            loginid: user.loginid,
            name: user.emname,
            orgid: user.orgid,
            titleid: user.titleid,
            type: "user"
          };
          this.defaultEmpByTree.push(delfaultUser);
        });
      }

      this.moa_page_explain = this.title;
    });
  }

  initSaveEnity() {
    this.saveEntity = {
      C_COMMUREC_type_i: null,//0表示渠道工作日报，1表示机构工作日报
      COMMURECID_i: 0,//新增时传0
      customer_id_i:"",//如果是渠道工作日报，调USP_A02_0030，传入sk_agency，如果是机构工作日报，调用USP_A02_0040，传入AGENCYCUSID
      VC_cus_REMARK_i: "",//客户备注	渠道或机构备注 用户填写
      CONTACTPERid_i: "",//客户联系人ID
      COMMUOBJECTNAME_i:"",//客户联系人姓名
      VC_CONTACT_i: "",//联系方式
      COMMUTIME_i: this.common.getNowFormatDate(),//沟通时间
      COMMUTYPE_i: "",//拜访类型
      EMPLOYEE_i: "",//员工
      REASON_i: "",//沟通事由
      VC_CONTENT_i: "",//沟通内容
      SUMMARY_i: "",//沟通总结
      REMARK_i: "",//沟通备注
      VC_FEATURE_i: "", //渠道或机构特点
      L_TRAIN_NUM_i: 0, //培训场次
      VC_INV_SUPPORT_i: "",//投研支持
      VC_IMP_PROJECT_i: "",//重要项目
      login_nm_i: ""//用户登录名称
    };

    this.pageField = {
      EMPLOYEE_i_name: "",
      customer_id_i_name: "",
      VC_INV_SUPPORT_i_name: ""
    };

  }

  setSaveEntity(detail) {
    let that = this;

    console.log(detail);
    this.saveEntity = {
      C_COMMUREC_type_i: detail[0],//0表示渠道工作日报，1表示机构工作日报
      COMMURECID_i: detail[1],//新增时传0
      customer_id_i:detail[12],//如果是渠道工作日报，调USP_A02_0030，传入sk_agency，如果是机构工作日报，调用USP_A02_0040，传入AGENCYCUSID
      VC_cus_REMARK_i: detail[4],//客户备注	渠道或机构备注 用户填写
      CONTACTPERid_i: detail[18],//客户联系人ID
      COMMUOBJECTNAME_i:detail[5],//客户联系人姓名
      VC_CONTACT_i: detail[19],//联系方式
      COMMUTIME_i: detail[2],//沟通时间
      COMMUTYPE_i: detail[6],//拜访类型
      EMPLOYEE_i: detail[24],//员工
      REASON_i: detail[9],//沟通事由
      VC_CONTENT_i: detail[10],//沟通内容
      SUMMARY_i: detail[11],//沟通总结
      REMARK_i: detail[17],//沟通备注
      VC_FEATURE_i: detail[14], //渠道或机构特点
      L_TRAIN_NUM_i: detail[23], //培训场次
      VC_INV_SUPPORT_i: detail[detail.length - 1],//投研支持
      VC_IMP_PROJECT_i: detail[15],//重要项目
      login_nm_i: ""//用户登录名称
    };

    if (detail[0] == "机构客户") {
      this.saveEntity.C_COMMUREC_type_i = 1;
      this.saveService.getOrganizationContacts(this.saveEntity.customer_id_i).subscribe(contacts => {
        /*console.log(contacts);
        var dataList = [];
        _.forEach(contacts, function (i) {
          let d = i.split("|");
          dataList.push(d);
        });
		that.organizationContacts = dataList;*/
		this.organizationContacts = contacts;
		console.log("机构客户ID数组：", this.organizationContacts);
      });
    } else {
      this.saveEntity.C_COMMUREC_type_i = 0;
      this.saveService.getAgencyContacts(this.saveEntity.customer_id_i).subscribe(contacts => {
        console.log(contacts);
        var dataList = [];
        _.forEach(contacts, function (i) {
          let d = i.split("|");
          dataList.push(d);
        });
        that.agencyContacts = dataList;
      });
    }

    _.forEach(this.contactTypeList, type => {
      if (type[1] == detail[6]) {
        that.saveEntity.COMMUTYPE_i = parseInt(type[0]);
      }
    });

    this.pageField = {
      EMPLOYEE_i_name: "",
      customer_id_i_name: detail[3],
      VC_INV_SUPPORT_i_name: detail[13]
    };

    console.log(detail[24]);
    that.saveEntity.EMPLOYEE_i = detail[24];
    that.pageField.EMPLOYEE_i_name = detail[7];

    this.storage.get("userInfo").then(user => {
      this.saveEntity.login_nm_i = user.loginid;
      /*that.pageField.EMPLOYEE_i_name = user.emname;
      that.saveService.getUsrIDByLoginNM(user.loginid).subscribe(usr_id => {
        console.log(usr_id);
        _.forEach(usr_id, function (i) {
          let d = i.split("|");
          that.saveEntity.EMPLOYEE_i = d[0];
        });
      });*/
    });

    this.storage.get("contact-user-list").then(u => {

      let tempDetail7 = detail[7].split(",");
      if (tempDetail7 && tempDetail7.length > 0) {
        _.forEach(tempDetail7, temp => {
          let t = _.filter(u, ["emname", temp, "loginid"]);
          console.log(t);
          if (t) {
            _.forEach(t, data => {
              that.saveService.getUsrIDFromOAServer(data["loginid"]).subscribe(usr_id => {
                if (usr_id && detail[24].indexOf(usr_id[0].usr_id) > -1) {
                  let delfaultUser = {
                    empid: data["empid"],
                    loginid: data["loginid"],
                    name: data["emname"],
                    orgid: data["orgid"],
                    titleid: data["titleid"],
                    type: "user"
                  };
                  that.defaultEmpByTree.push(delfaultUser);
                }

              });
            });
          }
        });
      }

      let tempDetail13 = detail[13].split(",");
      if (tempDetail13 && tempDetail13.length > 0) {
        _.forEach(tempDetail13, temp => {
          let t = _.filter(u, ["emname", temp, "loginid"]);
          console.log(t);
          if (t) {
            _.forEach(t, data => {
              that.saveService.getUsrIDFromOAServer(data["loginid"]).subscribe(usr_id => {
                if (usr_id && detail[detail.length - 1].indexOf(usr_id[0].usr_id) > -1) {
                  let delfaultUser = {
                    empid: data["empid"],
                    loginid: data["loginid"],
                    name: data["emname"],
                    orgid: data["orgid"],
                    titleid: data["titleid"],
                    type: "user"
                  };
                  that.defaultImpProject.push(delfaultUser);
                }

              });
            });
          }
        });
      }

    });

    console.log(this.saveEntity);
    console.log(this.pageField);
  }

  selectCommunicateTypeChange() {
    this.saveEntity.CONTACTPERid_i = "";
    this.saveEntity.COMMUOBJECTNAME_i = "";
    this.saveEntity.customer_id_i = "";
    this.pageField.customer_id_i_name = "";
    this.saveEntity.VC_CONTACT_i = "";
    this.saveEntity.VC_cus_REMARK_i = "";
    this.saveEntity.VC_INV_SUPPORT_i = "";
    this.pageField.VC_INV_SUPPORT_i_name = "";
    this.saveEntity.L_TRAIN_NUM_i = 0;
    this.defaultImpProject = [];
  }

  selectAgencyContactsChange() {
    console.log("---selectAgencyContactsChange---");
    _.forEach(this.agencyContacts, i => {
      let index = i.indexOf(this.saveEntity.CONTACTPERid_i);
      if (index != -1) {
        this.saveEntity.VC_CONTACT_i = i[3];
        console.log(this.saveEntity.VC_CONTACT_i);
      }
    });
  }

  /**
   * [chooseEmp 选择人员]
   * @param {[type]} item [description]
   */
  chooseEmp() {
    console.log("##authorization.detail.chooseEmpnames 选择外出人员");
    let that = this;
    let modal = this.modalCtrl.create(ContactChoosePage, {
      selected: this.defaultEmpByTree,
      isSelectUser: true,
      isSelectOne: false
    });

    modal.present();
    modal.onDidDismiss((data: any[]) => {
      console.info(data);
      if (data) {
        that.defaultEmpByTree = data;
        // this.saveEntity.EMPLOYEE_i = _.toString(_.map(data, "empid"));
        // this.pageField.EMPLOYEE_i_name = _.toString(_.map(data, "name"));
        this.saveEntity.EMPLOYEE_i = "";
        this.pageField.EMPLOYEE_i_name = "";
          that.saveService.getUsrIDFromOAServer(_.toString(_.map(data, "loginid"))).subscribe(usr_id => {
            console.log(usr_id);
            if (usr_id) {
              that.saveEntity.EMPLOYEE_i = _.toString(_.map(usr_id, "usr_id"));
              that.pageField.EMPLOYEE_i_name = _.toString(_.map(data, "name"));
            }
        });
      }
    });
  }

  chooseVC_INV_SUPPORT_i() {
    let that = this;
    let modal = this.modalCtrl.create(ContactChoosePage, {
      selected: this.defaultImpProject,
      isSelectUser: true,
      isSelectOne: false
    });

    modal.present();
    modal.onDidDismiss((data: any[]) => {
      console.info(data);
      if (data) {
        that.defaultImpProject = data;
        let login_nm = _.toString(_.map(data, "loginid"));
        that.pageField.VC_INV_SUPPORT_i_name = _.toString(_.map(data, "name"));
        that.saveService.getUsrIDFromOAServer(login_nm).subscribe(usr_id => {
          that.saveEntity.VC_INV_SUPPORT_i = _.toString(_.map(usr_id, "usr_id"));
        });

      }
    });
  }

  	chooseOrganization() {
  	    let chooseModal = this.modalCtrl.create(MarketingOrganizationChoosePage, {});
  	    chooseModal.onDidDismiss(data => {
  	        if (data && data != "close") {
  	            console.log(data);
  	            this.saveEntity.customer_id_i = data[0]; //机构客户ID
  	            this.pageField.customer_id_i_name = data[1]; //机构名称
  	            this.saveService.getOrganizationContacts(data[0]).subscribe(contacts => {
  	                this.organizationContacts = contacts;
					  console.log("机构客户ID数组：", this.organizationContacts);
					  this.saveEntity.CONTACTPERid_i = "";
					  this.saveEntity.COMMUOBJECTNAME_i = "";
  	            });
  	        }
  	    });
  	    chooseModal.present();
  	}

  chooseAgency() {
    let chooseModal = this.modalCtrl.create(MarketingAgencyChoosePage, {

    });
    chooseModal.onDidDismiss(data => {
      if (data && data != "close") {
        console.log(data);
        this.saveEntity.customer_id_i = data[0];//机构客户ID
        this.pageField.customer_id_i_name = data[1] + data[2] + data[3] + data[4];//机构名称
        this.saveService.getAgencyContacts(data[0]).subscribe(contacts => {
          console.log(contacts);
          var dataList = [];
          _.forEach(contacts, function (i) {
            let d = i.split("|");
            dataList.push(d);
          });
          this.agencyContacts = dataList;
        });
      }
    });
    chooseModal.present();
  }

  validateData() {
    let result = true;
    let message = "";
    if (this.saveEntity.C_COMMUREC_type_i === "" || this.saveEntity.C_COMMUREC_type_i == null) {
      console.log("validateData");
      console.log(this.saveEntity.C_COMMUREC_type_i);
      message = "请选择沟通类型";
      return message;
    }
    if (this.saveEntity.COMMUTIME_i === "") {
      message = "请选择沟通时间";
      return message;
    }
    if (this.saveEntity.VC_CONTENT_i.length >3000) {
      message = "沟通内容不能超过3000个字符";
      return message;
    }
    if (this.saveEntity.SUMMARY_i.length >3000) {
      message = "沟通总结不能超过3000个字符";
      return message;
    }
    if (this.saveEntity.customer_id_i === "") {
      if (this.saveEntity.C_COMMUREC_type_i == 1) {
        message = "请选择机构客户"
      } else {
        message = "请选择渠道";
      }
      return message;
    }
    if (this.saveEntity.EMPLOYEE_i === "") {
      message = "请选择员工";
      return message;
    }
    if (this.saveEntity.COMMUTYPE_i === "") {
      message = "请选择接触方式";
      return message;
    }
    if (_.parseInt(this.saveEntity.L_TRAIN_NUM_i) >= 100
      || _.parseInt(this.saveEntity.L_TRAIN_NUM_i) < 0) {
      message = "培训场次的数值只能介于[0-99]";
      return message;
	}
	//Names验证
	if (!this.checkString(this.saveEntity.COMMUOBJECTNAME_i)) {
		message = "姓名只能使用字母或汉字组成，只能使用英文逗号分割";
		return message;
	}
    return result;
  }

  clickEnable = true;
  /**
   * 保存工作日报
   */
  save() {
	let that = this;
	{
		this.saveEntity.COMMUOBJECTNAME_i = this.trimComma(this.saveEntity.COMMUOBJECTNAME_i);
		const _input = this.translateDataSource(this.saveEntity.COMMUOBJECTNAME_i);
		this.calcIdsAndNames(_input);
	}
    let validateResult = this.validateData();
    if (validateResult != true) {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: validateResult,
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
            }
          }
        ]
      });
      alert.present();
      return;
    }

    if (!this.clickEnable) {
      return;
    } else {
      this.clickEnable = false;
    }

    this.saveService.saveData(this.saveEntity).subscribe(result => {
      console.log(result, this.saveEntity);
      if (result) {
        result = result[0].split("|");
      }
      if (result && result[0] == 0) {
        let alert = this.alertCtrl.create({
          title: "提示",
          message: "保存成功",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
                this.storage.set("doRefresh", true);
                if (this.isEditData) {
                  let detail = this.navParams.get("detail");
                  detail[2] = this.saveEntity.COMMUTIME_i;
                  detail[5] = this.saveEntity.COMMUOBJECTNAME_i;
                  detail[4] = this.saveEntity.VC_cus_REMARK_i;
                  detail[13] = this.pageField.VC_INV_SUPPORT_i_name;
                  detail[19] = this.saveEntity.VC_CONTACT_i;
                  _.forEach(this.contactTypeList, type => {
                    if (type[0] == that.saveEntity.COMMUTYPE_i) {
                      detail[6] = type[1];
                    }
                  });
                  detail[9] = this.saveEntity.REASON_i;
                  detail[10] = this.saveEntity.VC_CONTENT_i;
                  detail[14] = this.saveEntity.VC_FEATURE_i;
                  detail[15] = this.saveEntity.VC_IMP_PROJECT_i;
                  detail[17] = this.saveEntity.REMARK_i;
                  detail[7] = this.pageField.EMPLOYEE_i_name;
                  detail[24] = this.saveEntity.EMPLOYEE_i;
				  detail[23] = this.saveEntity.L_TRAIN_NUM_i;
				  detail[18] = this.saveEntity.CONTACTPERid_i;
                }
                this.navCtrl.pop();
              }
            }
          ]
        });
        alert.present();
      } else {
        this.clickEnable = true;
      }
    });

    setTimeout(function () {
      that.clickEnable = true;
    }, 2000);
  }

  	//20170822-新增需求：选择拜访人添加到输入框中
	chooseVisitor(): void {
	    //检验Names是否符合汉字字母逗号的规范
	    if (!this.checkString(this.saveEntity.COMMUOBJECTNAME_i)) {
	        let alert = this.alertCtrl.create({
	            title: "温馨提示",
	            subTitle: "姓名只能使用字母或汉字组成，只能使用英文逗号分割",
	            buttons: ["确定"]
	        });
	        alert.present();
	        return;
	    }
	    //验证通过后清除Names左右逗号
	    this.saveEntity.COMMUOBJECTNAME_i = this.trimComma(this.saveEntity.COMMUOBJECTNAME_i);
	    //翻译Input数据源
	    let _input = this.translateDataSource(this.saveEntity.COMMUOBJECTNAME_i);
	    //创建选择框
	    {
	        let alert = this.alertCtrl.create({
	            title: "拜访人物"
	        });
	        this.organizationContacts.forEach((v: any) => {
	            alert.addInput({
	                type: "checkbox",
	                value: v.personid,
	                label: v.personname,
	                checked: this.getCheckedForInput(_input, v.personid)
	            });
	        });
	        alert.addButton({
	            text: "取消",
	            handler: () => {
	                this.calcIdsAndNames(_input);
	            }
	        });
	        alert.addButton({
	            text: "确定",
	            handler: (data: any) => {
	                //翻译Select数据源
	                let _select: any[] = this.translateDataSource(data);
	                //Input数据源和Select数据源整合成Output数据源
	                let _output: any[] = _input.filter((v: any) => {
	                    if (v.id === "0") return v;
	                });
	                _output.push(..._select);
	                //计算Names和IDs
	                this.calcIdsAndNames(_output);
	            }
	        });
	        alert.present();
	    }
	}
	checkString(str: string): boolean {
	    const regexp: any = /^[a-zA-Z\u4e00-\u9fa5,]+$/;
	    return regexp.test(str) || str === "";
	}
	trimComma(str: string): string {
	    if (str.constructor === String) return str.replace(/^,+/, "").replace(/,+$/, "");
	}
	getOrgContacItem(field: string) {
    if (this.organizationContacts) {
      let item = this.organizationContacts.find((v: any) => {
        if (v.personid === field || v.personname === field) return v;
      });
      return item;
    } else {
      return null;
    }
	}
	translateDataSource(dataSource: any): any[] {
	    let data: any[] = [];
	    //输入框翻译
	    if (dataSource.constructor === String && dataSource !== "") {
	        dataSource.split(",").forEach((v: any) => {
	            let item: any = {
	                id: this.getOrgContacItem(v) ? this.getOrgContacItem(v).personid : "0",
	                name: v
	            };
	            data.push(item);
	        });
	    }
	    //选择框翻译
	    else if (dataSource.constructor === Array && dataSource.length > 0) {
	        dataSource.forEach((v: any) => {
	            let item: any = {
	                id: v,
	                name: this.getOrgContacItem(v) ? this.getOrgContacItem(v).personname : "",
	            };
	            data.push(item);
	        });
	    }
	    return data;
	}
	getCheckedForInput(inputs, itemId): boolean {
	    let flag: boolean = false;
	    if (inputs.constructor === Array && inputs.length > 0) {
	        flag = inputs.find((v: any) => {
	            if (v.id === itemId) return true;
	        });
	    }
	    return flag;
	}
	calcIdsAndNames(array: any[]): void {
	    if (array.length > 0) {
	        let ids: string[] = [],
	            names: string[] = [];
	        array.forEach((v: any) => {
	            ids.push(v.id);
	            names.push(v.name);
	        });
	        this.saveEntity.CONTACTPERid_i = Array.from(new Set(ids)).join();
	        this.saveEntity.COMMUOBJECTNAME_i = names.join();
	    } else {
	        this.saveEntity.CONTACTPERid_i = "";
	        this.saveEntity.COMMUOBJECTNAME_i = "";
	    }
	    console.log("Names：", this.saveEntity.COMMUOBJECTNAME_i);
	    console.log("IDs：", this.saveEntity.CONTACTPERid_i);
	}
}
